package member

import (
	"context"
	"strconv"
	"strings"

	"mall/common/moneyx"
	"mall/service/backend/api/internal/logic/member/util"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/user/rpc/userclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type MemberListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMemberListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MemberListLogic {
	return &MemberListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MemberListLogic) MemberList(req *types.MemberListReq) (resp *types.MemberListResp, err error) {
	logx.Infof("MemberListReq : %+v ", req)

	var page int64 = 1
	var pageSize int64
	var status int32
	if req.Current > 1 {
		page = req.Current
	}
	if req.PageSize > 0 { // 指定，检查最大值
		pageSize = req.PageSize
		if pageSize > l.svcCtx.Config.Query.MaxAmount {
			pageSize = l.svcCtx.Config.Query.MaxAmount
		}
	} else { // 不指定，使用默认值
		pageSize = l.svcCtx.Config.Query.DefaultAmount
	}
	inStatus := strings.TrimSpace(req.Status)
	if len(inStatus) > 0 { // 不使用此字段为""，rpc对应为0
		if i, err := strconv.ParseInt(inStatus, 10, 32); err == nil {
			status = int32(i)
		}
	}
	orderBys := util.ParseSorter(req.Sorter)
	filterBys := util.ParseFilter(req.Filter)
	res, err := l.svcCtx.UserRpc.BackendMemberList(l.ctx, &userclient.BackendMemberListReq{
		Current:   page,
		PageSize:  pageSize,
		MemberIds: req.UserIds,
		Status:    status,
		Account:   req.Account,
		Nickname:  req.Nickname,
		Name:      req.Name,
		Email:     req.Email,
		Mobile:    req.Mobile,
		Search:    req.Search,
		OrderBy:   orderBys,
		FilterBy:  filterBys,
	})
	if err != nil {
		return nil, err
	}

	var list []*types.MemberInfo
	if len(res.List) > 0 {
		for _, item := range res.List {
			var memberAuth *types.MemberAuth
			if len(item.UserAuth) > 0 {
				for _, it := range item.UserAuth {
					memberAuth = &types.MemberAuth{
						Nickname:   it.Nickname,
						Avatar:     it.Avatar,
						Authorized: it.Authorized > 0,
						AuthType:   it.AuthType,
					}
					break
				}
			}
			var trans []*types.MemberTransaction
			if len(item.Trans) > 0 {
				for _, it := range item.Trans {
					assetTypeText := util.GetAssetTypeText(it.AssetType)
					sourceTypeText := util.GetSourceTypeText(it.SourceType)
					statusText := util.GetTransactionStatusText(it.Status)
					trans = append(trans, &types.MemberTransaction{
						Id:             it.Id,
						UserId:         it.UserId,
						UserName:       it.UserName,
						AssetType:      it.AssetType,
						AssetTypeText:  assetTypeText,
						ChangeType:     it.ChangeType,
						ChangeAmount:   it.ChangeAmount,
						Income:         it.ChangeType > 0,
						SourceType:     it.SourceType,
						SourceTypeText: sourceTypeText,
						SourceId:       it.SourceId,
						SourceDesc:     it.SourceDesc,
						Status:         it.Status,
						StatusText:     statusText,
						CreatedAt:      it.CreatedAt,
						UpdatedAt:      it.UpdatedAt,
					})
				}
			}
			genderText := util.GetGenderText(item.Gender)
			statusText := util.GetStatusText(item.Status)
			option := util.GetOptionByStatus(item.Status)
			list = append(list, &types.MemberInfo{
				Id:          item.Id,
				Account:     item.Account,
				Mobile:      item.Mobile,
				Email:       item.Email,
				Status:      item.Status,
				StatusText:  statusText,
				IsSystem:    item.IsSystem > 0,
				Nickname:    item.Nickname,
				Name:        item.Name,
				Url:         item.Url,
				DisplayName: item.DisplayName,
				Avatar:      item.Avatar,
				Gender:      item.Gender,
				GenderText:  genderText,
				Birthday:    item.Birthday,
				Country:     item.Country,
				Province:    item.Province,
				Gems:        moneyx.FormatGem(item.Gems),
				Integral:    item.Integral,
				Level:       item.Level,
				CanDisable:  option.CanDisable,
				CanEnable:   option.CanEnable,
				CanRemove:   option.CanRemove,
				CanRestore:  option.CanRestore,
				MemberAuth:  memberAuth,
				Trans:       trans,
			})
		}
	}

	return &types.MemberListResp{
		Current:  page,
		PageSize: pageSize,
		List:     list,
		Total:    res.Total,
	}, nil
}
